var express = require('express');
var router = express.Router();
//引入secretkey 
const {TOKEN_SECRETKEY} = require("../utils/secretKey")

//生成token的插件引入
var jwt = require('jsonwebtoken');

module.exports = router;

const {
  login,
  isExist,
  register
} = require('../service/usersService');


//登录
router.get('/login', async function(req, res, next) {
  const data = await login(req.query);

  //是否生成token判断----------------------------
  if(data.status){
    ////生成token--------------------------------
      const token = jwt.sign(
          {username:data.username},  // 该对象用于保存当前用户的相关信息

          TOKEN_SECRETKEY, // 密钥，任意字符串

          {expiresIn:'1h'} // 设置 token 有效期，单位 s
      )

      //将token发送给前端
      res.send({
          ...data,
          token
      });
  }else{
      res.send(data);
  }
});

//注册--用户名存在验证
router.get('/isExist', async function(req, res, next) {
  const data = await isExist(req.query);
  res.send(data);
});

//注册
router.post('/register', async function(req, res, next) {
  const data = await register(req.body);
  res.send(data);
});

//token验证
router.get('/isLogin', async function(req, res, next) {
  const token = req.get('Authorization').split(' ')[1];
  
  const {username} = jwt.verify(token,TOKEN_SECRETKEY);

  res.send({
    message:'用户信息获取成功',
    code: 1,
    data:{
      username
    }
  })
});